<?php namespace Core\Myapp\Database;

use Core\Myapp\Zobero;

class Processor extends Zobero
{
    protected $_pdo = null;

    protected $_query = '';

    protected $_paramsToExecute = array();

    protected function getPdo()
    {
        if(!$this->_pdo)
            $this->_pdo = $this->getSingleton('Core\Myapp\Database\Connection')->createConnection();
        return $this->_pdo;
    }

    protected function init($modelObject)
    {
        $this->setQuery($modelObject);
    }

    protected function prepare()
    {
        return $this->_pdo->prepare($this->getQuery());
    }

    protected function fetchAll()
    {
        return $this->_pdo->fetchAll();
    }

    public function save(Model $modelObject)
    {
        try {
            $this->getPdo();
            $this->setQuery($modelObject);
            $stm = $this->prepare();
            $stm->execute($this->getQueryBuider()->getParamsToExecute());
            $id = $this->getPdo()->lastInsertId();
            $primaryColumn = $modelObject->getPrimaryId();
            $modelObject->$primaryColumn = $id;
            return $modelObject;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function run(Model $modelObject)
    {
        $this->getPdo();
        $this->setQuery($modelObject);
        $stm = $this->prepare();
        $stm->execute($this->getQueryBuider()->getParamsToExecute());
        $object = $stm->fetch(\PDO::FETCH_OBJ);
        var_dump($object);
        if(!$object)
            return null;
        $propyties = get_object_vars($object);
        foreach($propyties as $key=>$value) {
            $modelObject->$key = $value;
        }
        return $modelObject;
    }

    protected function getQueryBuider()
    {
        return $this->getSingleton('Core\Myapp\Database\QueryBuider');
    }

    protected function setQuery($modelObject)
    {
        $this->_query = $this->getQueryBuider()->setModel($modelObject)->getQuery();
        return $this;
    }

    protected function setParamsToExcute()
    {
        $this->_paramsToExecute = $this->getQueryBuider()->getQuery();
    }

    protected function getQuery()
    {
        return $this->_query;
    }

    protected function getConditions()
    {

    }
}